package logic

import (
	"context"
	"errors"
	"zhongwen/cache"
	"zhongwen/models/mysql"
	"zhongwen/pkg"

	"zhongwen/zhongwenrpc/internal/svc"
	"zhongwen/zhongwenrpc/zhongwenrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *zhongwenrpc.ForgetPasswordRequest) (*zhongwenrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在查找失败")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if result != in.SendSms {
		return nil, errors.New("验证码错误")
	}
	if in.Password != in.NewPassword {
		return nil, errors.New("密码不一致")
	}
	if pkg.Md5Str(in.Password) == user.Password {
		return nil, errors.New("原密码与新密码一直")
	}
	user.Password = in.Password
	return &zhongwenrpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
